package com.sun.gis.utils;

import lombok.extern.slf4j.Slf4j;
import java.io.*;

/**
 * file io工具类
 *
 * @author ckk
 * @create 2022-08-06 19:44
 **/
@Slf4j
public class FileUtil {

    public static int totalLine = 0;

    public static void main(String[] args) throws IOException {
        String path = "F:\\ckk\\资料\\超图底图\\dxf做离线底图\\红庆河煤矿配准20220110\\处理dxf文件\\";
        String inputFileName = "采掘工程平面图（新）20220110";
        // 处理dxf文件，重复id的问题，lr_blocked_124_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1
        dealDxf(path, inputFileName);
    }

    /**
     * 处理dxf文件，_1_1_1_1 重复id的问题
     * @param path
     * @param inputFileName
     */
    public static void dealDxf(String path, String inputFileName){
        String suffix = ".dxf";
        String outputFileName = inputFileName + "_校正后";

        totalLine = 0;
        try {
            String inputFilePathName = path + inputFileName + suffix;
            String outputFilePathName = path + outputFileName + suffix;
            // 判断是否存在
            judgeFileExists(outputFilePathName, true);
            InputStreamReader isr = new InputStreamReader(new FileInputStream(inputFilePathName), "UTF-8");
            BufferedReader br = new BufferedReader(isr);

            StringBuffer sb = new StringBuffer();
            String temp = null;

            // 1000行写一次
            int page = 1000;
            int curLine = 0;
            while((temp = br.readLine()) != null){
                temp = dealLine(temp);
                sb.append(temp);
                sb.append("\r\n");
                curLine++;
                if(curLine == page){
                    // 追加写入
                    appendWriteFile(outputFilePathName, sb.toString());

                    // 重置
                    curLine = 0;
                    sb = new StringBuffer();
                }
            }
            // 追加写入
            appendWriteFile(outputFilePathName, sb.toString());

            br.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("一共处理："+totalLine+"行！！！");
    }

    /**
     * 处理dxf文件每行过长重复的id字符串，
     * 如：lr_blocked_124_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1
     * @param line
     * @return
     */
    public static String dealLine(String line){
//        String line = "lr_blocked_124_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1";
        if(line!=null && line.length() > 2 && line.substring(line.length()-2).equals("_1")){
            String[] split = line.split("_");
            int count = 0;
            String id = "";
            for(int i = split.length -1; i > 0; i--){
                if(split[i].equals("1")){
                    count++;
                }else {
                    for(int j = 0; j <= i; j++){
                        id += split[j] + "_";
                    }
                    break;
                }
            }
            id += count < 10 ? "00" + count : count < 100 ? "0" + count : count;
            line = id;
            System.out.println("line:"+line);
            totalLine++;
        }
        return line;
    }

    /**
     * 追加写文件
     * @param outputFilePathName
     * @param content
     * @return
     */
    public static void appendWriteFile(String outputFilePathName, String content){
        FileWriter fwriter = null;
        try {
            fwriter = new FileWriter(outputFilePathName, true);
            fwriter.write(content);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                fwriter.flush();
                fwriter.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 获取路径下所有文件或文件夹
     * @param path
     * @return
     */
    public static File[] listFiles(String path) {
        File f = new File(path);//获取路径  F:\测试目录
        if (!f.exists()) {
            System.out.println(path + " not exists");// 不存在就输出
            return null;
        }
        File[] files = f.listFiles();// 用数组接收
        return files;
    }

    /**
     * 读文件
     * @param fileName
     * @return
     */
    public static String readFile(String fileName) {
        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 写文件
     * @param outputPath
     * @param fileName
     * @param content
     * @return
     */
    public static boolean writeFile(String outputPath, String fileName, String content){
        File dir = new File(outputPath);
        boolean dirAvailable = FileUtil.judgeDirExists(dir, true);
        if(!dirAvailable){
            System.out.println("fileName:"+fileName+"，写入失败；原因：写入路径不可用！dir:"+outputPath);
            return false;
        }
        String filePath = outputPath + fileName;
        File file = new File(filePath);
        boolean fileAvailable = FileUtil.judgeFileExists(file, true);
        if(!fileAvailable){
            System.out.println("fileName:"+fileName+"，写入失败；原因：写入文件不可用！file:"+filePath);
            return false;
        }
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(filePath));
            // 执行写入操作
            bw.write(content);
            return true;
        } catch (IOException e) {
            log.error("fileName:"+fileName+"，写入失败！！！！！！！！！");
            return false;
        }finally {
            //关闭流
            try {
                bw.close();
            } catch (IOException e) {
                log.error("bw.close()失败。。");
            }
        }
    }

    /**
     * 判断文件是否存在，不存在 && create ，则创建
     * @param filePath
     * @param create true:不存在时，创建； false:不存在时，不创建
     * @return
     */
    public static boolean judgeFileExists(String filePath, boolean create) {
        return judgeFileExists(new File(filePath), create);
    }

    /**
     * 判断文件是否存在，不存在 && create ，则创建
     * @param file
     * @param create true:不存在时，创建； false:不存在时，不创建
     * @return
     */
    public static boolean judgeFileExists(File file, boolean create) {
        if (file.exists()) {
        } else {
            if(!create)return false;
            try {
                return file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    /**
     * 判断目录是否存在，不存在 && create ，则创建
     * @param dirPath
     * @param create true:不存在时，创建； false:不存在时，不创建
     * @return
     */
    public static boolean judgeDirExists(String dirPath, boolean create) {
        return judgeDirExists(new File(dirPath), create);
    }

    /**
     * 判断目录是否存在，不存在 && create ，则创建
     * @param dir
     * @param create true:不存在时，创建； false:不存在时，不创建
     * @return
     */
    public static boolean judgeDirExists(File dir, boolean create) {
        if (dir.exists()) {
            if (dir.isDirectory()) {
            } else {
                return mkdirs(dir, create);
            }
            return true;
        } else {
            return mkdirs(dir, create);
        }
    }

    /**
     * 递归删除目录下所有文件
     * @param dirOrFilePath
     */
    public static void delDir(String dirOrFilePath) {
        delDir(new File(dirOrFilePath));
    }

    /**
     * 递归删除目录下所有文件
     * @param dirOrFile
     */
    public static void delDir(File dirOrFile) {
        if (dirOrFile.isDirectory()) {
            File zFiles[] = dirOrFile.listFiles();
            for (File file2 : zFiles) {
                delDir(file2);
            }
            dirOrFile.delete();
        } else {
            dirOrFile.delete();
        }
    }

    /**
     * 将InputStream写入本地文件（将InputStream文件流转换为File文件）
     * @param destination
     * @param input
     * @return
     */
    public static boolean inputStreamToFile(String destination, InputStream input){
        int index;
        byte[] bytes = new byte[1024];
        FileOutputStream downloadFile = null;
        try {
            downloadFile = new FileOutputStream(destination);
            while ((index = input.read(bytes)) != -1) {
                downloadFile.write(bytes, 0, index);
                downloadFile.flush();
            }
        } catch (FileNotFoundException e) {
            log.error("error:inputStreamToFile:FileNotFoundException");
            return false;
        } catch (IOException e) {
            log.error("error:inputStreamToFile:IOException");
            return false;
        }finally {
            try {
                input.close();
                downloadFile.close();
            } catch (IOException e) {
            }
        }
        return true;
    }

    private static boolean mkdirs(File dirPathFile, boolean create){
        if(!create)return false;
        return dirPathFile.mkdirs();
    }

}